package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.ArticleDto;
import com.itheima.dto.FrontUserDto;
import com.itheima.dto.PageDto;
import com.itheima.entity.YddArticle;
import com.itheima.entity.YddCate;
import com.itheima.entity.YddUser;
import com.itheima.entity.YddUserData;
import com.itheima.service.YddArticleService;
import com.itheima.service.YddCateService;
import com.itheima.service.YddUserDataService;
import com.itheima.service.YddUserService;
import com.itheima.untils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private YddUserService yddUserService;

    @Autowired
    private YddArticleService yddArticleService;

    @Autowired
    private YddUserDataService yddUserDataService;

    @Autowired
    private YddCateService yddCateService;


    /**
     * 用户资料回显
     */
    @GetMapping("/getUserInfo")
    public R<FrontUserDto> getUserInfo(HttpServletRequest request){
        //设置用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseToken(token);
        Integer id = (Integer) claims.get("id");
        YddUser user = yddUserService.getById(id);

        //设置文章发布数
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getAuthor,"admin");
        int count = yddArticleService.count(queryWrapper);

        //设置收藏数
        LambdaQueryWrapper<YddUserData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(YddUserData::getUserId,id).eq(YddUserData::getType,1);
        int count1 = yddUserDataService.count(lambdaQueryWrapper);

        //设置点赞数
        LambdaQueryWrapper<YddUserData> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(YddUserData::getUserId,id).eq(YddUserData::getType,2);
        int count2 = yddUserDataService.count(lambdaQueryWrapper1);

        FrontUserDto frontUserDto = new FrontUserDto();
        frontUserDto.setUserInfo(user);
        frontUserDto.setArticleNum(count);
        frontUserDto.setCollectNum(count1);
        frontUserDto.setZanNum(count2);
        return R.success(frontUserDto);
    }

    @PostMapping("/update")
    public R<String> update(@RequestBody YddUser yddUser){
        yddUserService.updateById(yddUser);
        return R.success("修改成功");
    }

    /**
     * 查询我的文章
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/myArticle")
    public R<PageDto> myArticle(Integer page, Integer limit, HttpServletRequest request){
        //根据token获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseToken(token);
        Integer id = (Integer) claims.get("id");

        Page<YddArticle> yddArticlePage = new Page<>(page, limit);
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq( YddArticle::getUserId, id);
        queryWrapper.orderByDesc(YddArticle::getCreateDate);
        Page<YddArticle> articlePage = yddArticleService.page(yddArticlePage, queryWrapper);

        //封装数据到pageDto
        PageDto pageDto = new PageDto();
        pageDto.setPageSize(yddArticlePage.getSize());
        pageDto.setCurrentPage(yddArticlePage.getCurrent());
        pageDto.setTotalPages(yddArticlePage.getPages());
        pageDto.setCount(yddArticlePage.getTotal());
        pageDto.setData(articlePage.getRecords());
        return R.success(pageDto);
    }

    /**
     * 我的收藏/点赞
     * @param type
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/userDataList")
    public R<HashMap> userDataList(Integer type,Integer page, Integer limit, HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseToken(token);
        Integer id = (Integer) claims.get("id");

        LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUserData::getUserId,id).eq(YddUserData::getType,type);
        List<YddUserData> userData = yddUserDataService.list(queryWrapper);

        //获取到文章id的集合
        List<Integer> collect = userData.stream().map(item -> {
            Integer articleId = item.getArticleId();
            return articleId;
        }).collect(Collectors.toList());

        Page<YddArticle> yddArticlePage = new Page<>(page,limit);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(YddArticle::getId,collect).orderByDesc(YddArticle::getCreateDate);
        Page<YddArticle> articlePage = yddArticleService.page(yddArticlePage, wrapper);

        List<YddArticle> records = articlePage.getRecords();
        List<ArticleDto> articleDtos = records.stream().map(item -> {
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(item, articleDto);

            Integer cateid = item.getCateid();
            YddCate cate = yddCateService.getById(cateid);
            String catename = cate.getCatename();

            articleDto.setCatename(catename);
            return articleDto;

        }).collect(Collectors.toList());

        PageDto pageDto = new PageDto();
        pageDto.setData(articleDtos);
        pageDto.setTotalPages(articlePage.getPages());
        pageDto.setPageSize(articlePage.getSize());
        pageDto.setCount(articlePage.getTotal());
        pageDto.setCurrentPage(articlePage.getCurrent());

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list",pageDto);
        return R.success(hashMap);
    }

    /**
     * 添加文章
     * @param yddArticle
     * @param request
     * @return
     */
    @PostMapping("/addArticle")
    public R<String> addArticle(@RequestBody YddArticle yddArticle,HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseToken(token);
        Integer id = (Integer) claims.get("id");

        //公共字段无法满足项目内相应时间格式，进行重新设置
        long timeMillis = System.currentTimeMillis();
        yddArticle.setCreateDate(timeMillis);
        yddArticle.setUserId(id);
        yddArticleService.save(yddArticle);


        return R.success("操作成功");

    }

    /**
     * 修改文章
     * @param yddArticle
     * @return
     */
    @PostMapping("/editArticle")
    public R<String> editArticle(@RequestBody YddArticle yddArticle){
        long now = System.currentTimeMillis();
        yddArticle.setUpdateDate(now);
        yddArticleService.updateById(yddArticle);
        return R.success("操作成功");
    }

    /**
     * 删除文章
     * @param id
     * @return
     */
    @GetMapping("/delArticle")
    public R<String> delArticle(Integer id){
        yddArticleService.removeById(id);

        //删除userdata表中数据
        LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUserData::getArticleId,id);
        yddUserDataService.remove(queryWrapper);

        return R.success("删除成功");
    }

    /**
     * 点赞/取消点赞和收藏/取消收藏
     * @param type
     * @param article_id
     * @param action
     * @param request
     * @return
     */
    @GetMapping("/userDataHandle")
    public R<String> userDataHandle(String type, String article_id, String action, HttpServletRequest request) {
        yddUserDataService.removeByType(type, article_id, action, request);
        return R.success("操作成功");
    }

}
